import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from sklearn.metrics import roc_curve,roc_auc_score


    
def get_default_device():
    """默认选择 gpu"""
    if torch.cuda.is_available():
        # 使用第二张
        if torch.cuda.device_count() > 1:
            return torch.device('cuda:1')
        else:
            return torch.device('cuda:0') 
    else:
        return torch.device('cpu')
    
def to_device(data, device):
    """将 tensor 移动到指定的 device"""
    if isinstance(data, (list,tuple)):
        return [to_device(x, device) for x in data]
    return data.to(device, non_blocking=True)


def plot_history(history, show_flag = False, save_path = None):

    losses1 = [x['val_loss1'] for x in history]
    losses2 = [x['val_loss2'] for x in history]
    plt.plot(losses1, '-x', label="loss1")
    plt.plot(losses2, '-x', label="loss2")
    plt.xlabel('epoch')
    plt.ylabel('loss')
    plt.legend()
    plt.title('Losses vs. No. of epochs')
    plt.grid()
    if show_flag:
        plt.show()
    if save_path is not None:
        plt.savefig(save_path)


def plot_ROC(y_test,y_pred, show_flag = False, save_path = None):
    fpr,tpr,tr=roc_curve(y_test,y_pred)
    auc=roc_auc_score(y_test,y_pred)
    idx=np.argwhere(np.diff(np.sign(tpr-(1-fpr)))).flatten()

    plt.xlabel("FPR")
    plt.ylabel("TPR")
    plt.plot(fpr,tpr,label="AUC="+str(auc))
    plt.plot(fpr,1-fpr,'r:')
    plt.plot(fpr[idx],tpr[idx], 'ro')
    plt.legend(loc=4)
    plt.grid()
    if show_flag:
        plt.show()
    if save_path is not None:
        plt.savefig(save_path)
    return tr[idx]